#!/usr/bin/env python3
# coding: utf-8


import os.path
import DBUtils.PooledDB as pooleddb
import pymysql
import configparser


def getconfigure(home):
    def _loadmyconf(path):
        parser = configparser.ConfigParser()
        parser.read(os.path.join(path, ".my.cnf"))
        return dict(
            host=parser.get("mysql", "host") or "localhost",
            user=parser.get("mysql", "user") or "root",
            passwd=parser.get("mysql", "password") or "",
            db=parser.get("mysql", "database") or "workingdb",
            )
    settings = dict()
    for subdir in os.listdir(home):
        subpath = os.path.join(home, subdir)
        if os.path.isfile(os.path.join(subpath, ".my.cnf")):
            settings[subdir] = _loadmyconf(subpath)
    return settings


class ConnFactory(object):

    POOLKWGS = dict(
        mincached=0,
        maxcached=0,
        maxshared=0,
        maxconnections=0,
        blocking=False,
        maxusage=None,
        setsession=None,
        reset=True,
        failures=None,
        ping=1,
        )

    def __init__(self, path):
        self.setting = getconfigure(path)
        self.factory = dict()
        for domain, setting in self.setting.items():
            kwgs = dict(self.POOLKWGS, **setting)
            self.factory[domain] = pooleddb.PooledDB(pymysql, **kwgs)

    def __getitem__(self, domain):
        if domain not in self.factory:
            return
        return self.factory[domain]

    def __call__(self, domain):
        return self.factory[domain].connection()
